package com.wen.imagezip.service;

import com.wen.imagezip.util.ImageCompressionUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
@Service
public class ImageProcessingService {

    /**
     * 处理图片上传和压缩
     *
     * @param file 上传的图片文件
     * @return 压缩后的图片字节数组
     * @throws IOException
     */
    public CompletableFuture<byte[]> processImage(MultipartFile file) throws IOException {
        return CompletableFuture.supplyAsync(() -> {
            try {
                // 读取图片
                BufferedImage image = ImageIO.read(file.getInputStream());

                // 动态计算压缩质量
                float compressionQuality = ImageCompressionUtil.dynamicCalculateCompressionQuality(image);

                // 压缩图片
                byte[] compressedImageBytes = ImageCompressionUtil.compressImage(image, compressionQuality);

                return compressedImageBytes;
            } catch (IOException e) {
                throw new RuntimeException("Error processing image", e);
            }
        });
    }
}
